/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年2月24日 下午10:58:59
 */
package com.lenovo.lmrp.server.assigntracer.domain.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.lenovo.lmrp.api.constant.EngineerState;
import com.lenovo.lmrp.api.constant.MessageTemplateType;
import com.lenovo.lmrp.api.model.entity.EngineerPO;
import com.lenovo.lmrp.api.model.entity.EngineerTerminalPO;
import com.lenovo.lmrp.api.model.entity.MessageTemplatePO;
import com.lenovo.lmrp.api.model.entity.ProjectEngineerPO;
import com.lenovo.lmrp.api.model.entity.ProjectExtensePO;
import com.lenovo.lmrp.api.model.entity.TicketExtensePO;
import com.lenovo.lmrp.api.model.entity.TicketPO;
import com.lenovo.sdc.framework.dao.ADaoFactory;
import com.lenovo.sdc.framework.dao.ICommonDAO;
import com.lenovo.sdc.framework.dao.RecordFilter;
import com.lenovo.sdc.framework.util.AttributeBean;
import com.lenovo.sdc.framework.util.CommonUtil;
import com.lenovo.sdc.framework.util.Condition;
import com.lenovo.sdc.framework.util.Condition.OperatorEnum;
import com.lenovo.sdc.framework.util.Condition.RelationEnum;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * 
 * @author songyz
 * @version $Id: DBSelector.java, v 0.1 2016年2月24日 下午10:58:59 songyz Exp $
 */
public class QuerySelector {
	/**
	 * 查询消息模板
	 * 
	 * @return
	 */
	public List<MessageTemplatePO> getMessageTemplateList(String itsmCode, MessageTemplateType type) {
		try (ICommonDAO dao = ADaoFactory.getDefault().createDAO("lmrp")) {
			RecordFilter filter = new RecordFilter();
			filter.addCondition(new Condition<String, Object>("itsmcode", itsmCode))
					.addCondition(new Condition<String, Object>("messagetype", type.getType()), RelationEnum.AND);
			return dao.filteByCondition(MessageTemplatePO.class, filter);
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.DB_QUERY_FAILED, e);
		}
	}

	/**
	 * 查询工程师
	 * 
	 * @param itsmCode
	 * @param filter
	 * @return
	 */
	public List<EngineerPO> getEngineerPOList(String itsmCode, RecordFilter filter) {
		try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
			return dao.filteByCondition(EngineerPO.class, filter);
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.DB_QUERY_FAILED, e);
		}
	}

	/**
	 * 根据工单地域，项目，优先分组，查询工程师列表
	 * 
	 * @param itsmCode
	 * @param ticketId
	 *            工单编号
	 * @param groupto
	 *            抢单的工程师分组顺位
	 * @return
	 */
	public List<EngineerPO> getEngineerPOsByGroupto(String itsmCode, TicketPO ticketPO, int groupto) {
		List<EngineerPO> engineerPOs = new ArrayList<>();
		try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
			if (Objects.isNull(ticketPO))
				return new ArrayList<>(0);

			// 从工作流传来的扩展类如果为空，去数据库查询
			TicketExtensePO ticketExtensePO = ticketPO.getOthers();
			if (Objects.isNull(ticketExtensePO)) {
				ticketExtensePO = dao.get(TicketExtensePO.class, ticketPO.getId());
				if (Objects.isNull(ticketExtensePO)) {
					return new ArrayList<>(0);
				}
				ticketPO.setOthers(ticketExtensePO);
			}
			// 根据工单的地域，拼出一个地域字符串
			String region = "";
			AttributeBean extBean = ticketExtensePO.getAttributeBean();
			String provincename = extBean.getAttribute("provincename","");
			region = region + provincename + "|";
			String cityname = extBean.getAttribute("cityname","");
			region = region + cityname + "|";
			String county = extBean.getAttribute("county","");
			region = region + county;

			RecordFilter recordFilter = new RecordFilter();
			// 根据项目和分组筛选
			List<ProjectEngineerPO> projectEngineerPOs = dao.filteByCondition(ProjectEngineerPO.class,
					recordFilter.addCondition(new Condition<String, Object>("projectid", ticketPO.getProjectId()))
							.addCondition(new Condition<String, Object>("groupto", groupto), RelationEnum.AND)
							.addCondition(new Condition<String, Object>("region", region),
									RelationEnum.AND)
					.addCondition(new Condition<String, Object>("status", 1), RelationEnum.AND));
			projectEngineerPOs.forEach(projectEngPo -> {
				engineerPOs.add(dao.get(EngineerPO.class, projectEngPo.getEngineerId()));
			});
			return engineerPOs;
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.DB_QUERY_FAILED, e);
		}
	}

	/**
	 * 根据工单编号，工单的地域，查询第四顺位的工程师
	 * 
	 * @param itsmCode
	 * @param projectId
	 * @return
	 * @return
	 */
	public ProjectEngineerPO getTicketFinalEngineer(String itsmCode, TicketPO ticketPO) {
		try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
			if (Objects.isNull(ticketPO))
				return null;

			// 从工作流传来的扩展类如果为空，去数据库查询
			TicketExtensePO ticketExtensePO = ticketPO.getOthers();
			if (Objects.isNull(ticketExtensePO)) {
				ticketExtensePO = dao.get(TicketExtensePO.class, ticketPO.getId());
				if (Objects.isNull(ticketExtensePO)) {
					return null;
				}
				ticketPO.setOthers(ticketExtensePO);
			}
			// 根据工单的地域，拼出一个地域字符串
			String region = "";
			AttributeBean extBean = ticketExtensePO.getAttributeBean();
			Object provincename = extBean.get("provincename");
			region = region + (Objects.isNull(provincename) ? "%" : (String) provincename) + "|";
			Object cityname = extBean.get("cityname");
			region = region + (Objects.isNull(cityname) ? "%" : (String) cityname) + "|";
			Object county = extBean.get("county");
			region = region + (Objects.isNull(county) ? "%" : (String) county);

			// 根据项目和抢单顺位筛选
			List<ProjectEngineerPO> projectEngineerPOs = dao.filteByCondition(ProjectEngineerPO.class,
					new RecordFilter().addCondition(new Condition<String, Object>("projectid", ticketPO.getProjectId()))
							.addCondition(new Condition<String, Object>("groupto", 4), RelationEnum.AND)
							.addCondition(new Condition<String, Object>("region", region, OperatorEnum.LIKE),
									RelationEnum.AND)
							.addCondition(new Condition<String, Object>("status", 1), RelationEnum.AND));
			for (ProjectEngineerPO projectEngPo : projectEngineerPOs) {
				projectEngPo.setEngineer(dao.get(EngineerPO.class, projectEngPo.getEngineerId()));
				return projectEngPo;
			}
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.DB_QUERY_FAILED, e);
		}
		return null;
	}

	/**
	 * 根据工单地域，查询工程师列表
	 * 
	 * @param itsmCode
	 * @param ticketId
	 * @return
	 */
	public List<EngineerPO> getEngineerPOsByTicketScope(String itsmCode, String ticketId) {
		try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
			TicketExtensePO ticketExtensePO = dao.get(TicketExtensePO.class, ticketId);
			RecordFilter recordFilter = new RecordFilter();
			if (Objects.nonNull(ticketExtensePO)) {
				if (Objects.nonNull(ticketExtensePO.getAttributeBean().get("provincename")))
					recordFilter.addCondition(new Condition<String, Object>("province",
							ticketExtensePO.getAttributeBean().get("provincename")));
				if (Objects.nonNull(ticketExtensePO.getAttributeBean().get("cityname")))
					recordFilter.addCondition(
							new Condition<String, Object>("city", ticketExtensePO.getAttributeBean().get("cityname")));
				if (Objects.nonNull(ticketExtensePO.getAttributeBean().get("county")))
					recordFilter.addCondition(
							new Condition<String, Object>("county", ticketExtensePO.getAttributeBean().get("county")));
			}
			return dao.filteByCondition(EngineerPO.class, recordFilter);
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.DB_QUERY_FAILED, e);
		}
	}

	/**
	 * 查询某一工程师所有的cid集合
	 * 
	 * @param itsmCode
	 * @param engineerId
	 * @return
	 */
	public String getEngineerOnLineCids(String itsmCode, String engineerId) {
		if (CommonUtil.isNullOrEmpty(engineerId)) return null;
		List<EngineerTerminalPO> eglist = getEngineerTerminalPOList(itsmCode,
				new RecordFilter().addCondition(new Condition<String, Object>("engineerid", engineerId)).addCondition(
						new Condition<String, Object>("status", EngineerState.ONLINE.getState()), RelationEnum.AND));
		if (eglist.size() != 0)
			return eglist.get(0).getCid();
		return null;
	}

	/**
	 * 查询工程师设备
	 * 
	 * @param itsmCode
	 * @param addCondition
	 * @return
	 */
	public List<EngineerTerminalPO> getEngineerTerminalPOList(String itsmCode, RecordFilter filter) {
		try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
			return dao.filteByCondition(EngineerTerminalPO.class, filter);
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.DB_QUERY_FAILED, e);
		}
	}

	/**
	 * 获取工单
	 * 
	 * @param itsmCode
	 * @param ticketId
	 * @return
	 */
	public TicketPO getTicketPO(String itsmCode, String ticketId) {
		try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
			return dao.get(TicketPO.class, ticketId);
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.DB_QUERY_FAILED, e);
		}
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	public TicketExtensePO getTicketExtense(String itsmCode, String id) {
		try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
			return dao.get(TicketExtensePO.class, id);
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.DB_QUERY_FAILED, e);
		}
	}

	/**
	 * 获取项目扩展信息
	 * 
	 * @param itsmcode
	 * @param ticketid
	 * @return
	 */
	public List<Map<String, String>> getProjectExtense(String itsmcode, String ticketid) {
		List<Map<String, String>> list = new ArrayList<>(0);
		try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmcode)) {
			TicketPO ticketPO = dao.get(TicketPO.class, ticketid);
			ProjectExtensePO extensePO = dao.get(ProjectExtensePO.class, ticketPO.getProjectId());
			if (Objects.isNull(extensePO) || Objects.isNull(extensePO.getAttributeBean())) {
				return list;
			}
			List<Map<String, String>> listJosn = (List<Map<String, String>>) extensePO.getAttributeBean()
					.get("rolelist");
			return listJosn;
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.DB_QUERY_FAILED, e);
		}
	}
}
